<template>
  <div>
    <myHeader></myHeader>
    <div style="height:1000px;"></div>
    <div v-if="btnFlag" class="myTop" @click="backTop()">
      <img :src="myTop" />
      <div>回到顶部</div>
    </div>
  </div>
</template>
<script>
import myHeader from "../components/header";
import myTop from "../assets/img/top.png";
export default {
  components: {
    myHeader
  },
  data() {
    return {
      myTop: myTop,
      //v-if为true显示，false消失
      btnFlag: false,
      //记录屏幕滑动的值
      scrollTop: 0,
      small: false,
      big: false
    };
  },
  created() {
    var getIsBig = this.$store.getters.getIsBig;
    if (getIsBig === true) {
      this.big = true;
      this.small = false;
    } else {
      this.big = false;
      this.small = true;
    }
  },
  // vue的两个生命钩子，这里不多解释。
  // window对象，所有浏览器都支持window对象。它表示浏览器窗口，监听滚动事件
  mounted: function() {
    window.addEventListener("scroll", this.scrollToTop);
    // console.log(this.scrollToTop);
  },
  destroyed: function() {
    window.removeEventListener("scroll", this.scrollToTop);
  },
  computed: {
    count() {
      return this.$store.getters.getIsBig;
    }
  },
  watch: {
    count(getIsBig) {
      if (getIsBig === true) {
        this.big = true;
        this.small = false;
      } else {
        this.big = false;
        this.small = true;
      }
    }
  },
  methods: {
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑

    backTop() {
      const that = this;
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          that.scrollTop + ispeed;
        if (that.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 16);
    },

    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop() {
      const that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      if (that.scrollTop > 60) {
        that.btnFlag = true;
      } else {
        that.btnFlag = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.myTop {
  width: 60px;
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 99;
  img {
    width: 100%;
  }
  cursor: pointer;
}
</style>
